import threading
import time
from threading import Semaphore
rwait=Semaphore(1)
wwait=Semaphore(1)
bwait=Semaphore(0)
rcount=0


def reader(buffer,num,starttime,ctime):

    time.sleep(starttime)
    rwait.acquire()
    print('时间点  '+str((int(time.strftime('%S'))-start)%60)+'  reader  '+str(num)+'  等待读')
    rwait.release()
    if buffer==0:
        bwait.acquire()
    rwait.acquire()
    global rcount
    if rcount==0:
        wwait.acquire()
    rcount += 1
    print('时间点  ' + str((int(time.strftime('%S')) - start) % 60) + '  reader  ' + str(num) + '  开始读')
    file=open('data.txt',mode='r',encoding='utf-8')
    print(file.read())
    file.close()
    bwait.release()
    rwait.release()
    time.sleep(ctime)
    print('时间点  '+str((int(time.strftime('%S'))-start)%60)+'  reader  '+str(num)+ ' 读完')

    rwait.acquire()
    rcount -=1
    if rcount==0:
        wwait.release()

    rwait.release()




def writer(buffer,num,starttime,ctime):

    time.sleep(starttime)
    print('时间点  ' + str((int(time.strftime('%S')) - start) % 60) + '  writer  ' + str(num) + '  等待写')
    wwait.acquire()
    print('时间点  '+str((int(time.strftime('%S'))-start)%60)+'  writer  '+str(num)+'  写数据')
    file=open('C:\\Users\\曾令杰\\PycharmProjects\\reader_first\\data.txt',mode='r+',encoding='utf-8')
    file.write(input())
    data=file.readlines()
    time.sleep(ctime)
    print('时间点  '+str((int(time.strftime('%S'))-start)%60)+'  writer  '+str(num)+'  退出写操作')
    buffer=len(data)
    wwait.release()
    bwait.release()






if __name__ == '__main__':

    num=[]
    rwlist=[]
    starttime=[]
    continuetime=[]
    file=open('C:\\Users\\曾令杰\\PycharmProjects\\reader_first\\data.txt','r+',encoding='utf-8')
    file.seek(0)
    file.truncate()
    data=file.readlines()
    buffer=len(data)
    with open('C:\\Users\\曾令杰\\PycharmProjects\\reader_first\\input.txt', 'r', encoding='gb18030', errors='ignore') as f:
        data = f.readlines()[1:]
        for x in data:
            x=x.split()
            num.append(int(x[0]))
            rwlist.append(x[1])
            starttime.append(int(x[2]))
            continuetime.append(int(x[3]))
    start = int(time.strftime('%S'))
    for i in range(len(rwlist)):
        print('时间点  '+str((int(time.strftime('%S'))-start)%60)+'  线程  '+str(num[i])+'  set up\n', end='')
        if rwlist[i] == 'R':
            t = threading.Thread(target=reader,args=(buffer,num[i],starttime[i],continuetime[i]))
            t.start()
        else:
            t = threading.Thread(target=writer,args=(buffer,num[i],starttime[i],continuetime[i]))
            t.start()
